package ex1;
import java.io.*;
import java.net.*;

/*
  This is the client side of the UDP client/server example
  It reads a string in from the console, sends it to the
  server to be converted into upper case, and then prints
  out the result
*/

class UDPClient {
    public static void main (String args[])
      throws Exception
      /* if you have time at the end take a look at the exceptions that might be raised and think about nicer ways of handling them */
      {
	String 			sentence, modifiedSentence;
        BufferedReader 		inFromUser;
        DatagramSocket 		clientSocket;
        InetAddress 		serverIPAddress;
        byte[] 			sendData, receiveData;
        DatagramPacket 		sendPacket, receivePacket;

	// prepare to get input from the console
	// A BufferedReader provides nice methods like readLine()
	// and is more efficient than just using InputStreamReader
	inFromUser = new BufferedReader(new InputStreamReader(System.in));

	// create the client socket
	// This is just a generic Socket object - we need to specify
	// the address (or name) of machine running your server,
	// plus the port number your server is listening on
	// if this method doesn't throw an exception, then we have
	// successfully opened a connection to the server
	// If you get an error like "connection refused", then the
	// server probably isn't running
	clientSocket = new DatagramSocket();
	serverIPAddress = InetAddress.getByName("localhost");

        // arrange arrays of bytes for the data sent and recieved to go into
        // this gives us a chance to try something a bit more low level than the streams and readers we used in the TCP example
        sendData = new byte[1024];
        receiveData = new byte[1024];

        // get the string from System.in and turn it into a byte array to send
        System.out.println("Type something now");
        sentence = inFromUser.readLine();
        sendData = sentence.getBytes();

        // build a packet to send in a UDP datagram
        // has contents, content length and a 2 part destination address
	sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, 4321);

        // now, actually send it
        clientSocket.send(sendPacket);

        // and get a reply:
	receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);

        // and extract the response into a string
        // trim gets rid of any trailing nulls etc that may have come through
	modifiedSentence = new String(receivePacket.getData()).trim();

        // print the response and close the socket to finish
	System.out.println("FROM SERVER: " + modifiedSentence);
	clientSocket.close();
    }
}
